package sing.core.ext.view

import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.provider.MediaStore
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

// 保存图片
fun Bitmap.saveImage(path_name: String,cr: ContentResolver,context: Context) {
    // 测试输出
    var out: FileOutputStream? = null
    try {
        out = FileOutputStream(path_name)
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    }
    try {
        if (null != out) {
            this.compress(Bitmap.CompressFormat.PNG, 100, out)
            out.flush()
            out.close()
        }
    } catch (e: IOException) {

    }
    MediaStore.Images.Media.insertImage(cr, path_name, "title", "description")
    var intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    var uri = Uri.fromFile(File(path_name));
    intent.data = uri;
    context.sendBroadcast(intent);
}

/**
 * 根据控件比例剪裁bitmap成一个固定大小的图片
 * @param bitmap 需要裁剪的源图
 * @param num1  宽比例
 * @param num2  高比例
 * @param isRecycled 是否回收
 * @return  裁剪之后的bitmap
 */
fun Bitmap.imageCrop(bitmap: Bitmap, num1: Float, num2: Float, isRecycled: Boolean): Bitmap {
    val w = bitmap.width
    val h = bitmap.height
    val retX: Int
    val retY: Int //裁剪的起始点
    val nw: Int
    val nh: Int //裁剪下来newBitmap的宽和高
    if (w > h) { //宽大于高
        if (h > w * num2 / num1) { //如果跟比例走的话，高符合条件，则保存宽度，截取高
            nw = w
            nh = (w * num2 / num1).toInt()
            retX = 0
            retY = (h - nh) / 2
        } else { //如果高达不到比例要求的，则保持高截取宽
            nw = (h * num1 / num2).toInt()
            nh = h
            retX = (w - nw) / 2
            retY = 0
        }
    } else { //高大于宽，根据比例宽高比大于1，高肯定符合条件，所以直接截取
        nw = w
        nh = (w * num2 / num1).toInt()
        retX = 0
        retY = (h - nh) / 2
    }
    val bmp = Bitmap.createBitmap(bitmap, retX, retY, nw, nh, null, false)
    if (isRecycled && bitmap != null && bitmap != bmp && !bitmap.isRecycled) {
        bitmap.recycle() //回收原图片
    }
    return bmp
}